package com.ikas.ai.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 加密工具类
 * @author HXH
 */
@SuppressWarnings("all")
public class EncryptUtil {

    private static Logger logger = LoggerFactory.getLogger(EncryptUtil.class);
    private static final String TYPE_AES = "AES";
    private static final String TYPE_DES = "DES";
    private static String mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static Random random = new Random();
    private static MessageDigest messagedigest = null;

    //密钥 (需要前端和后端保持一致)
    private static final String KEY = "abcdefgabcdefg12";
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("MD5FileUtil messagedigest初始化失败", e);
        }
    }

    /**
     * aes解密
     * @param content 内容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String content) {
        try {
            return aesDecrypt(content, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * aes加密
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content) {
        try {
            return aesEncrypt(content, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 将byte[]转为各种进制的字符串
     * @param bytes byte[]
     * @param radix 可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，超出范围后变为10进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
    }

    /**
     * base 64 encode
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : Base64.decodeBase64(base64Code);
    }


    /**
     * 加密JDK1.8
     * @param str
     * @return java.lang.String
     * @author dolyw.com
     * @date 2018/8/21 15:28
     */
    public static String encodeStr(String str) throws UnsupportedEncodingException {
        byte[] encodeBytes = java.util.Base64.getEncoder().encode(str.getBytes("utf-8"));
        return new String(encodeBytes);
    }

    /**
     * 解密JDK1.8
     * @param str
     * @return java.lang.String
     * @author dolyw.com
     * @date 2018/8/21 15:28
     */
    public static String decodeStr(String str) throws UnsupportedEncodingException {
        byte[] decodeBytes = java.util.Base64.getDecoder().decode(str.getBytes("utf-8"));
        return new String(decodeBytes);
    }

    /**
     * AES加密
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }


    /**
     * AES加密为base 64 code
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * 将base 64 code AES解密
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            String test = "123456";
            String key = "password123";
            logger.debug("加密前的字符：" + test);
            String dst = encrypt(test, key);
            logger.debug("加密后的字符：" + dst);
            logger.debug("解密后的字符：" + decrypt(dst, key));

            String str = aesEncode(test, key);
            logger.debug(str);
            String str2 = aesDecode(str, key);
            logger.debug(str2);

            String content = GuidUtil.getCheckCode4();
            System.out.println("加密前：" + content);
            System.out.println("加密密钥和解密密钥：" + KEY);
            String encrypt = aesEncrypt(content, KEY);
            System.out.println("加密后：" + encrypt);
            String decrypt = aesDecrypt(encrypt, KEY);
            System.out.println("解密后：" + decrypt);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * AES加密
     * @param content
     * @param key
     * @return
     */
    public static String aesEncode(String content, String key) {
        try {
            // 1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance(TYPE_AES);
            // 2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            keygen.init(128, random);

            // 3.产生原始对称密钥
            SecretKey originalKey = keygen.generateKey();
            // 4.获得原始对称密钥的字节数组
            byte[] raw = originalKey.getEncoded();
            // 5.根据字节数组生成AES密钥
            SecretKey aesKey = new SecretKeySpec(raw, TYPE_AES);
            // 6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance(TYPE_AES);
            // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            // 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byteEncode = content.getBytes("utf-8");
            // 9.根据密码器的初始化方式--加密：将数据加密
            byte[] byteAES = cipher.doFinal(byteEncode);
            // 10.将加密后的数据转换为字符串
            // 这里用Base64Encoder中会找不到包，解决办法：
            // 在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
            return Base64Util.encode(byteAES).trim();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * AES解密
     * @param content
     * @param key
     * @return
     */
    public static String aesDecode(String content, String key) {
        try {
            // 1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance(TYPE_AES);
            // 2.根据ecnodeRules规则初始化密钥生成器
            // 生成一个128位的随机源,根据传入的字节数组
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            keygen.init(128, random);

            // 3.产生原始对称密钥
            SecretKey originalKey = keygen.generateKey();
            // 4.获得原始对称密钥的字节数组
            byte[] raw = originalKey.getEncoded();
            // 5.根据字节数组生成AES密钥
            SecretKey aesKey = new SecretKeySpec(raw, TYPE_AES);
            // 6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance(TYPE_AES);
            // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            // 8.将加密并编码后的内容解码成字节数组
            byte[] byteContent = Base64Util.decode(content);
            // 解密
            byte[] byteDecode = cipher.doFinal(byteContent);
            return new String(byteDecode, "utf-8").trim();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        // 如果有错就返加nulll
        return null;
    }

    /**
     * MD5加密
     * @param source
     * @return
     */
    public static final String md5(String source) {
        try {
            byte[] strTemp = source.getBytes();
            // 使用MD5创建MessageDigest对象
            MessageDigest mdTemp = messagedigest;
            mdTemp.update(strTemp);
            // MD5 的计算结果是一个 128 位的长整数，用字节表示就是 16 个字节
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            // 从第一个字节开始，对 MD5的每一个字节转换成 16进制字符的转换
            for (int i = 0; i < j; i++) {
                byte b = md[i];
                // 将没个数(int)b进行双字节加密
                str[k++] = hexDigits[b >> 4 & 0xf];
                str[k++] = hexDigits[b & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5Encode(String source) {
        char[] charArray = source.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = messagedigest.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 字符串加密
     * @param str 待加密的字符串
     * @return 加密后的字符串
     */
    public static String encode(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        byte[] buff = str.getBytes();
        int j;
        int k;
        int m;
        int len = mstr.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buff.length; i++) {
            j = (byte) random.nextInt(6);
            buff[i] = (byte) ((int) buff[i] ^ j);
            k = (int) buff[i] % len;
            m = (int) buff[i] / len;
            m = m * 8 + j;
            sb.append(mstr.substring(k, k + 1) + mstr.substring(m, m + 1));
        }
        return sb.toString();
    }

    /**
     * 字符串解密
     * @param str 待解密的字符串
     * @return 解密后的字符串
     */
    public static String decode(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        int j = 0;
        int k = 0;
        int m = 0;
        int n = 0;
        int len = mstr.length();
        byte[] buff = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i += 2) {
            k = mstr.indexOf(str.charAt(i));
            m = mstr.indexOf(str.charAt(i + 1));
            j = m / 8;
            m = m - j * 8;
            buff[n] = (byte) (j * len + k);
            buff[n] = (byte) ((int) buff[n] ^ m);
            n++;
        }
        return new String(buff);
    }

    /**
     * 加密字节数组
     * @param bytes 需加密的字节数组
     * @param key   加密密钥
     * @return 加密后的字节数组
     */
    public static byte[] encrypt(byte[] bytes, String key) {
        try {
            SecureRandom secureRandom = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance(TYPE_DES);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, secureKey, secureRandom);
            // 获取数据并加密，执行加密操作
            return cipher.doFinal(bytes);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return new byte[0];
    }

    /**
     * 加密字符串
     * @param source 需加密的字符串
     * @param key    加密密钥
     * @return 加密后的字符串
     */
    public static String encrypt(String source, String key) {
        return NumUtil.bytes2hex(encrypt(source.getBytes(), key));
    }

    /**
     * 解密字节数组
     * @param bytes 需解密的字节数组
     * @param key   解密密码
     * @return 解密后的字节数组
     */
    public static byte[] decrypt(byte[] bytes, String key) {
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom secureRandom = new SecureRandom();
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(TYPE_DES);
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance(TYPE_DES);
            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, secureKey, secureRandom);
            // 真正开始解密操作
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new byte[0];
    }

    /**
     * 解密字符串
     * @param source 需解密的字符串
     * @param key    秘钥
     * @return 解密后的字符串
     */
    public static String decrypt(String source, String key) {
        return new String(decrypt(NumUtil.hex2bytes(source), key));
    }

    public static String getFileMD5String(File file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        FileChannel ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        messagedigest.update(byteBuffer);
        return bufferToHex(messagedigest.digest());
    }

    public static String getMD5String(String s) {
        return getMD5String(s.getBytes());
    }

    public static String getMD5String(byte[] bytes) {
        messagedigest.update(bytes);
        return bufferToHex(messagedigest.digest());
    }

    private static String bufferToHex(byte[] bytes) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte[] bytes, int m, int n) {
        StringBuilder stringbuffer = new StringBuilder(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuilder stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}
